import store from '@/store'

import {
	MUTATIONS as UserMutai
} from '@/store/modules/userStore'

// 手机号校验
export const getMobileIsFun = num => {
	return /^1[0-9]{10}$/.test(num);
};

// 查找JSON数组中对象属性所对应的下标
export function getArrayIndexFun(arrayObj, key, value) {
	return arrayObj.findIndex(item => item[key] === value)
}

// 判断是否是数组
export const isArrayFun = (array) => {
	return Object.prototype.toString.call(array) === '[object Array]'
}

// 判断是否是对象
export const isObjectFun = (object) => {
	return Object.prototype.toString.call(object) === '[object Object]'
}

// 判断是否是空对象
export const isEmptyObjectFun = (object) => {
	return Object.keys(object).length === 0
}

// 判断是否是空
export const isEmptyFun = (value) => {
	if (isArrayFun(value)) {
		return value.length === 0
	}
	if (isObjectFun(value)) {
		return isEmptyObjectFun(value)
	}
	return !value
}

// 对象转URL形式
export const setUrlEncodeFun = (obj = {}) => {
	const result = []
	for (const key in obj) {
		const item = obj[key]
		if (!item) {
			continue
		}
		if (isArrayFun(item)) {
			item.forEach((val) => {
				result.push(key + '=' + val)
			})
		} else {
			result.push(key + '=' + item)
		}
	}
	return result.join('&')
}

// 筛选JSON数组中属性值相匹配的对象
export function	getfilterValueArrayFun(arrayList, key, value) {
	let result = arrayList.filter(item => item[key] == value);
	return result.length ? result[0] : {};
}

// JSON对象转换为URL参数
export function setJsonObjToUrlFun(url) {
    return Object.keys(url).map(key => key + '=' + url[key]).join('&');
}

// 获取URL参数并转换成JSON对象
export function setUrlToObjFun(url) {
	let list = url.split('&');
	let result = {};
	for (let key of list) {
		result[key.split('=')[0]] = key.split('=')[1];
	}
	return result;
}

// 页面跳转事件
export const setNavigateFunTo = (url, query = {}) => {
	if (!url || url.length == 0) {
		return false
	}

	const queryStr = !isEmptyFun(query) ? '?' + setUrlEncodeFun(query) : '';

	return uni.navigateTo({
		url: `/${url}${queryStr}`,
	})
}

// 轮播图跳转事件
export async function setJumpFunTo(item = {}, index = 0) {
	
	// #ifdef APP-PLUS
	// page_url 页面路径
	// page_url_is_login 该页面是否需要登录
    if(item.page_url && item.page_url_is_login) {
        // 支付前验证是否已登录
        if (await store.dispatch('SHOW_LOGIN_APP_GET_FUN')) return;
        return uni.navigateTo({
            url: item.page_url
        })
    }else if(item.page_url) {
        return uni.navigateTo({
            url: item.page_url
        })
    }
	// #endif
	
	// type 页面类型
	// type 2：web-view H5页面
	if(item.type === 2 && item.href_url) {
		const href_url = encodeURIComponent(item.href_url);
		return uni.navigateTo({
			url: `/secondary/webViewPage/webViewPage?src=${href_url}`
		})
	}
	
	// type 3：普通页面
	if(item.type === 3 && item.page_url) {
		return uni.navigateTo({
			url: item.page_url
		})
	}
	
	// poolType 赏池类型
	// type 4：赏池页面   poolType 0：全局赏
	if(item.type === 4 && item.poolType === 0){
		const url = `/secondary/globalRewardPage/globalRewardPage?id=${item.reward_pool_id}&type=${item.type}&poolTypeSence=${item.poolTypeSence}`;
		return uni.navigateTo({
			url
		})
	}
	  
	// type 4：赏池页面   poolType 5：飞机赏
	if(item.type === 4 && item.poolType === 5){
		const url = `/secondary/infinitePage/infinitePage?id=${item.reward_pool_id}`;
		return uni.navigateTo({
			url
		})
	}
}

// 异步等待事件
export function setAsyncFunWait(time) {
	return new Promise((resolve) => {
		setTimeout(() => {
			resolve()
		}, time)
	})
}

// 数据修复到指定长度
export function setFixArrayFun(arrayList, arrayLength) {
	const listLen = arrayList.length;
	if (listLen <= 0 || arrayLength <= 0) return [];
	if (arrayLength < listLen) return arrayList.slice(0, arrayLength);

	const result = [];
	for (let i = 0; i < Math.floor(arrayLength / listLen); i++) {
		result.push(...arrayList);
	}
	result.push(...arrayList.slice(0, arrayLength % listLen));
	
	return result;
}

// APP获取设备信息: oaid
export function getOAIDDeviceFun() {
	return new Promise((succ) => {
		plus.device.getOAID({
			success: function(e) {
				succ.call(self, e)
			},
			fail: function(e) {
				succ.call(self, {})
			}
		});
	})
}

// APP获取设备信息: imsi, imei, uuid, idfa
export function getInfoDeviceFun() {
	return new Promise((succ) => {
		plus.device.getInfo({
			success: function(e) {
				succ.call(self, e)
			},
			fail: function(e) {
				succ.call(self, {})
			}
		});
	})
}

// APP保存图片
export function setAppSaveImgFun(url) {
	uni.showModal({
		title: '提示',
		content: '是否保存到相册吗？',
		success: function(res) {
			if (res.confirm) {
				uni.downloadFile({
					url,
					success: (res) => {
						if (res.statusCode === 200) {
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function() {
									uni.showToast({
										title: "保存成功，请去相册查看！",
										icon: "none"
									});
								},
								fail: function() {
									uni.showModal({
										content: '检测到您没打开获取信息功能权限，是否前去设置打开？',
										confirmText: "确认",
										cancelText: '取消',
										success: (res) => {
											if (res
												.confirm) {
												uni.openSetting({
													success: (
														res
													) => {
														uni.showToast({
															title: "请重新长按保存图片！",
															icon: "none"
														});
													}
												})
											} else {
												uni.showToast({
													title: "保存失败，请打开权限功能重试！",
													icon: "none"
												});
											}
										}
									})
								}
							});
						}
					}
				})
			}
		}
	});

}


// 是否获取用户信息
export function setAuthUserInfoUsers(show) {
	store.commit(UserMutai.SHOW_AUTH_USER_INFO_SET_FUN, show)
}

// 是否获取手机信息
export async function setAuthPhoneUsers(show, type) {
	if (show && type !== 'onceRelogin') {
		await store.dispatch('RE_LOGIN_GET_FUN');
	}
	await store.commit(UserMutai.SHOW_AUTH_PHONE_SET_FUN, show)
}

// 是否显示手机号微信授权弹框
export function authPhoneSetFun() {
	if (!store.getters.isAuthPhoneUsers) {
		setAuthPhoneUsers(true)
		return false
	} else {
		return true
	}
}

// 是否显示用户信息微信授权弹框
export function authUserInfoSetFun() {
	return true;
}

// 微信登录
export function wxAuthSetFun() {
	if (authUserInfoSetFun()) {
		if (!authPhoneSetFun()) return false
	} else {
		return false
	}
	return true
}

// 换箱操作
export function boxIndexSetFun(index) {
	store.commit(UserMutai.BOX_INDEX_SET_FUN, index)
}

// APP场景： 未绑定手机号时，提示绑定手机号
export function addPhoneSetFun() {
	if (!store.getters.isAuthPhoneUsers) {
		uni.showToast({
			icon: "error",
			title: '请绑定手机号！',
			mask: true,
		})

		setTimeout(() => {
			uni.navigateTo({
				url: "/app_page/settings/settings",
			})
		}, 300);

		return true;
	} else {
		return false;
	}
}

export function setParseFunTime(datetime = 0, formatStr = 'YYYY-mm-dd HH:MM') {
	if (typeof datetime === 'number') {
		datetime = new Date(datetime)
	}
	let result;
	let timeObj = {
		"Y+": datetime.getFullYear().toString(),
		"m+": (datetime.getMonth() + 1).toString(),
		"d+": datetime.getDate().toString(),
		"H+": datetime.getHours().toString(),
		"M+": datetime.getMinutes().toString(),
		"S+": datetime.getSeconds().toString()
	};
	for (let item in timeObj) {
		result = new RegExp("(" + item + ")").exec(formatStr);
		if (result) {
			formatStr = formatStr.replace(result[1], (result[1].length == 1) ? (timeObj[item]) : (timeObj[item].padStart(result[1].length, "0")))
		};
	};
	return formatStr;
}

// 获取当天倒计时 type: objType || stringType
export function setCountFunDown(type) {
	let currentTime = new Date();
	
	let hour = currentTime.getHours();
	let min = currentTime.getMinutes();
	let sec = currentTime.getSeconds();

	let h = 24 - hour;
	if (min > 0 || sec > 0) {
		h -= 1
	}
	let m = 60 - min;
	if (sec > 0) {
		m -= 1
	}
	if (m == 60) {
		m = 0
	}
	let s = 60 - sec;
	if (s == 60) {
		s = 0
	}
	
	h = h.toString();
	m = m.toString();
	s = s.toString();
	if (h.length == 1) {
		h = '0' + h
	}
	if (m.length == 1) {
		m = '0' + m
	}
	if (s.length == 1)
		s = '0' + s
	let result = h + ' : ' + m + ' : ' + s
	
	if(type === 'objType') {
		return { h, m, s };
	}else{
		return result;
	}
}


export function setTimeFunDown(timeStr) {
	timeStr = timeStr.replace(/-/g, "/")

	let sec = (new Date(timeStr).getTime() - new Date().getTime()) / 1000;
	let d = parseInt(sec / (24 * 60 * 60))
	let h = parseInt(sec / (60 * 60) % 24);
	let m = parseInt(sec / 60 % 60);
	let s = parseInt(sec % 60);
	let timeObj = {
		text: d + '天' + h + '时' + m + '分' + s + '秒',
		flag: true
	}
	if (d <= 0 && h <= 0 && m <= 0 && s <= 0) {
		timeObj.flag = false;
	}

	return timeObj
}

// 秒数时间
export function setDayTimeFunFormat(secs) {
	if (!secs) {
		return "已结束";
	}
	
	let day = Math.floor(secs / 3600 / 24);
	
	let hr = Math.floor(secs / 3600 % 24);
	hr = hr < 10 ? "0" + hr : hr;
	
	let min = Math.floor(secs / 60 % 60);
	min = min < 10 ? "0" + min : min;
	
	let sec = Math.floor(secs % 60);
	sec = sec < 10 ? "0" + sec : sec;

	if (day <= 0) {
		return hr + ":" + min + ":" + sec;
	} else {
		return day + "天 " + hr + ":" + min + ":" + sec;
	}
}

// 把总秒数 转成成 时分秒倒计时
export function secondToDate(result){
	var h = Math.floor(result / 3600) < 10 ? '0'+Math.floor(result / 3600) : Math.floor(result / 3600);
	var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
	var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
	
	let timeObj = {
		h,
		m,
		s,
		flag: true
	}
	if (h <= 0 && m <= 0 && s <= 0) {
		timeObj.flag = false;
	}
	
	return timeObj;
}


export const navTabFun = function(list = []) {
	const tabAreaList = list.map(item => {
		return {
			...item,
			id: 'tab-id' + parseInt(Math.random() * 100000),

		}
	})

	this.currentIndex = 0;
	this.poScrollViewInto = '';

	const navTabClickFun = (e) => {
		const index = +(e.target.dataset.current || e.currentTarget.dataset.current);
		const item = tabAreaList[index];
		
		this.$emit('tabtap', index);
		if (this.currentIndex === index) return;
		this.$emit('change', index);
		
		this.currentIndex = index;
		
		setTimeout(() => {
			this.poScrollViewInto = item.id
		}, 200)
	}

	return {
		currentIndex: this.currentIndex,
		poScrollViewInto: this.poScrollViewInto,
		tabAreaList,
		navTabClickFun,
	}
}

/**  
 * 节流 ：一个事件在n秒内被多次触发，但绑定的函数在期间只会执行一次（也就是降低函数的执行频率）
 * 场景：输入框发送补全查询，秒杀、抢卷按钮，按下一次后，接下来几秒不让用户继续按(也可用锁实现)
 * isImmediate 是否立即执行
 */  
export const throttleFun = function(fn, wait = 500, isImmediate = false) {  
  let flag = true;  
  if (isImmediate) {  
    return function() {  
      if (flag) {  
        fn.apply(this, arguments);  
        flag = false;  
        setTimeout(() => {  
          flag = true  
        }, wait)  
      }  
    }  
  }  
  return function() {  
    if (flag == true) {  
      flag = false  
      setTimeout(() => {  
        fn.apply(this, arguments)  
        flag = true  
      }, wait)  
    }  
  }  
}  

/**  
 * 防抖：
 * 一个事件在触发后，设置定时器，若n秒内该事件没有再次发生，那么执行这个函数，
 * 如果n秒内该事件再次发生了，那么定时器重新开始计时。
 * 场景：每次 resize / scroll 触发统计事件，文本输入的验证
 * isImmediate 是否立即执行
 */  
export const debounceFun = function(fn, wait = 500, isImmediate = false) {  
  let timerId = null;  
  let flag = true;  
  if (isImmediate) {  
    return function() {  
      clearTimeout(timerId);  
      if (flag) {  
        fn.apply(this, arguments);  
        flag = false  
      }  
      timerId = setTimeout(() => {  
        flag = true  
      }, wait)  
    }  
  }  
  return function() {  
    clearTimeout(timerId);  
    timerId = setTimeout(() => {  
      fn.apply(this, arguments)  
    }, wait)  
  }  
}